package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
@Slf4j
@Api(tags = "套餐相关接口")
public class SetmealController {
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private SetmealDishService setmealDishService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private DishService dishService;

    /**
     * 添加套餐
     * @param setmealDto
     * @return
     */
    @CacheEvict(value ="setmealCache" ,allEntries = true )
    @PostMapping
    @ApiOperation(value = "新增套餐接口")
    public R<String> save(@RequestBody SetmealDto setmealDto) {
//        日志，传回来的套餐信息
        log.info("传回的套餐信息：{}", setmealDto);
//        自定义方法保存套餐和菜品信息
        setmealService.saveWithDish(setmealDto);
        return R.success("套餐修改成功");
    }

    /**
     * 分页展示套餐数据
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    @ApiOperation(value = "套餐分页查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "每页记录数",required = true),
            @ApiImplicitParam(name = "name",value = "套餐名称",required = false)
    })
    public R<Page> page(Integer page, Integer pageSize, String name) {
//        日志
        log.info("当前页：{}，页大小：{}，套餐名称：{}", page, pageSize, name);
//        分页构造器
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);
        Page<SetmealDto> dtoPage = new Page<>();
//        条件构造器
        LambdaQueryWrapper<Setmeal> lwq = new LambdaQueryWrapper<>();
        lwq.like(null != name, Setmeal::getName, name).orderByDesc(Setmeal::getUpdateTime);
//        将拼接的条件进行查询，封装进pageInfo中
        setmealService.page(pageInfo, lwq);
//        对象拷贝，目的是为了重设records
        BeanUtils.copyProperties(pageInfo, dtoPage, "records");
        List<Setmeal> records = pageInfo.getRecords();
//        开启流，设置records属性
        List<SetmealDto> list = records.stream().map((item) -> {
//            创建setmealDto对象
            SetmealDto setmealDto = new SetmealDto();
            //将records中的内容拷到setmealDto中
            BeanUtils.copyProperties(item, setmealDto);
            //分类id
            Long categoryId = item.getCategoryId();
            //根据分类id查询分类对象
            Category category = categoryService.getById(categoryId);
            //分类名称
//            对对象进行非空判断
            if (null != category) {
//                分类名称
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());
//        封装records
        dtoPage.setRecords(list);
//        返回结果
        return R.success(dtoPage);
    }

    /**
     * 逻辑删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @Transactional
    @CacheEvict(value ="setmealCache" ,allEntries = true )
    @ApiOperation(value = "套餐删除接口")
    public R<String> deleted(@RequestParam List<Long> ids) {
//        日志
        log.info("要逻辑删除的id：{}", ids.toString());
//        查询条件构造器
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
//        一共要删两张表，一张是套餐表，一张是套餐里的菜品表
//        拼接id,where id in(......),逻辑删除套餐表,如果套餐在售就不能删除
        queryWrapper.in(Setmeal::getId, ids).eq(Setmeal::getStatus, "1");
        int count = setmealService.count(queryWrapper);
//        count大于0说明套餐在售，不能删除
        if (count > 0) {
//            抛出自定义的业务异常
            throw new CustomException("套餐正在售卖中，不能删除");
        }
//        不满足if条件说明不在售，可以删除，执行删除操作
        setmealService.removeByIds(ids);
//删除套餐里包含的菜品表，
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(wrapper);

        return R.success("删除成功");
    }

    /**
     * 修改套餐状态，启售，停售
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmealCache",allEntries = true)
    @ApiOperation(value = "更改套餐状态接口")
    public R<String> update(@PathVariable Integer status, @RequestParam List<Long> ids) {
//        日志
        log.info("前端传回的状态：{}，要更改状态的id：{}", status, ids);
//        查询条件构造器
        LambdaUpdateWrapper<Setmeal> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(null != status, Setmeal::getStatus, status).in(Setmeal::getId, ids);
        setmealService.update(updateWrapper);
        return R.success("修改成功");
    }

    /**
     * 根据条件查询套餐数据，套餐种类
     *开启Redis缓存
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @ApiOperation(value = "套餐条件查询接口")
    @Cacheable(value = "setmealCache",key = "#setmeal.categoryId + '_' + #setmeal.status",unless = "#result.data.size() == 0")
    public R<List<Setmeal>> list(Setmeal setmeal) {
        log.info("套餐查询列表:{}", setmeal);
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());
        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = setmealService.list(queryWrapper);

        return R.success(list);
    }

    /**
     * 套餐菜品展示
     * @param id
     * @return
     */
    @GetMapping("/dish/{id}")
    @ApiOperation(value = "根据id展示套餐菜品接口")
    @Cacheable(value = "setmealCache",key = "#id + '_' ",unless = "#result.data.size() == 0")
    public R<List<SetmealDish>> dishList(@PathVariable Long id) {
//        日志
        log.info("当前菜品id:{}", id);
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(null != id, SetmealDish::getSetmealId, id).orderByDesc(SetmealDish::getUpdateTime);
        List<SetmealDish> list = setmealDishService.list(queryWrapper);
        return R.success(list);
    }
    /**
     * 查询数据，回填要修改的套餐
     * 清除Redis缓存
     * @param id
     * @return
     */

    @GetMapping("/{id}")
    public R<SetmealDto> edit(@PathVariable Long id){
        log.info("需要修改回填的菜品的id：{}",id);
        SetmealDto setmealDto = setmealService.getByIdWithSetmeal(id);

        return R.success(setmealDto);
    }
    /**
     * 修改套餐
     * @param setmealDto
     * @return
     */
    @CacheEvict(value ="setmealCache" ,allEntries = true )
    @PutMapping
    @ApiOperation(value = "修改套餐接口")
    public R<String> update(@RequestBody SetmealDto setmealDto){
//        日志
        log.info("修改后的菜品信息：{}",setmealDto.toString());
        setmealService.updateWithDishes(setmealDto);
        return R.success("修改成功");
    }


}